//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Checkbox, List, message, Modal, Space } from 'antd';
import { useDataViewStores } from '../../store';
import { type MemberInfo, list_member } from "@/api/project_member";
import { request } from '@/utils/request';
import { get_session } from '@/api/user';
import UserPhoto from '@/components/Portrait/UserPhoto';
import { update_view_perm } from "@/api/project_dataview";
import { UserOutlined } from '@ant-design/icons';

interface UserPermModalProps {
    onClose: () => void;
}

const UserPermModal = observer((props: UserPermModalProps) => {
    const dataViewStore = useDataViewStores();

    const [memberList, setMemberList] = useState<MemberInfo[]>([]);
    const [updateUserIdList, setUpdateUserIdList] = useState(dataViewStore.projectStore.viewInfo?.extra_update_user_id_list ?? []);
    const [hasChange, setHasChange] = useState(false);

    const loadMemberList = async () => {
        const sessionId = await get_session();
        const res = await request(list_member(sessionId, dataViewStore.projectStore.projectId, false, []));
        setMemberList(res.member_list);
    };

    const updateVierPerm = async () => {
        const sessionId = await get_session();
        await request(update_view_perm({
            session_id: sessionId,
            project_id: dataViewStore.projectStore.projectId,
            view_id: dataViewStore.projectStore.dataViewId,
            extra_update_user_id_list: updateUserIdList,
        }));
        message.info("设置成功");
        setHasChange(false);
        props.onClose();
    };

    useEffect(() => {
        loadMemberList();
    }, []);

    return (
        <Modal open title="设置修改权限" mask={false}
            bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll" }}
            okText="设置" okButtonProps={{ disabled: hasChange == false }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                updateVierPerm();
            }}>
            <List rowKey="member_user_id" dataSource={memberList} pagination={false}
                renderItem={item => (
                    <List.Item extra={
                        <Checkbox checked={item.can_admin || updateUserIdList.includes(item.member_user_id)} disabled={item.can_admin}
                            onChange={e => {
                                e.stopPropagation();
                                if (e.target.checked) {
                                    const tmpUserIdList = updateUserIdList.slice();
                                    tmpUserIdList.push(item.member_user_id);
                                    setUpdateUserIdList(tmpUserIdList);
                                } else {
                                    const tmpUserIdList = updateUserIdList.filter(memberUserId => memberUserId != item.member_user_id);
                                    setUpdateUserIdList(tmpUserIdList);
                                }
                                setHasChange(true);
                            }}>可编辑</Checkbox>
                    }>
                        <Space>
                            <UserPhoto logoUri={item.logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                            {item.display_name}
                        </Space>
                    </List.Item>
                )} />
        </Modal>
    );
});

const ProjectMemberListPanel = () => {
    const [showModal, setShowModal] = useState(false);

    return (
        <div style={{ backgroundColor: "white", padding: "6px 10px", cursor: "pointer" }} title='设置权限'
            onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                setShowModal(true);
            }}>
            <UserOutlined />
            {showModal == true && (
                <UserPermModal onClose={() => setShowModal(false)} />
            )}
        </div>
    );
};

export default ProjectMemberListPanel;